package com.readingtree.library.service;

import com.readingtree.library.domain.SecurityUser;
import com.readingtree.library.domain.repository.JwtTokenRepository;
import com.readingtree.library.util.JWTHelper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * Created by Administrator on 2017/4/19.
 */
@Service("jwtTokenService")
public class JWTTokenServiceImpl implements JWTTokenService{

    @Autowired
    private JwtTokenRepository tokenRepository;

    @Override
    public String createJWTToken(SecurityUser user) {
        String secret = UUID.randomUUID().toString();
        String token = JWTHelper.createJWT(user.getUsername(), user.getId()
                , user.getRole().getName(), secret);
        user.setSecret(secret);
        user.setExpiration(7200L);
        user.setToken(token);
        tokenRepository.save(user);
        return token;
    }

    @Override
    public boolean checkJWTToken(String token) {
        if(StringUtils.isEmpty(token)){
            return false;
        }
        SecurityUser user = tokenRepository.findOne(token);
        if(user!=null && user.getId()>0){
            Claims claims =  JWTHelper.parseJWT(token, user.getSecret());
            if(claims!=null){
                String username = (String)claims.get("username");
                String target = user.getUsername();
                if(!StringUtils.isEmpty(username)&& !StringUtils.isEmpty(target)&&username.equals(target)){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void removeJWTToken(String token) {
        tokenRepository.delete(token);
    }

    @Override
    public SecurityUser getUserFromToken(String token) {
        if(!StringUtils.isEmpty(token)){
            return tokenRepository.findOne(token);
        }
        return null;
    }
}
